package com.vf.s.mvc.city.service;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.vf.core.render.RenderBean;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.city.BizCity;
import com.vf.s.common.model.city.BizCityMenu;

public class BizCityService {

	public BizCity findById(Controller para) {
		return BizCity.dao.findById(para.getPara("cityId"));
	}
	
	
	public Page<BizCity> listData(Controller para) {
		int pageNumber = para.getParaToInt("page", 1);
		int pageSize = para.getParaToInt("limit", 10);
		String keyword = para.getPara("keyword");

		String sqlExceptSelect = " FROM " + BizCity.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%' OR   O.CODE '%" + keyword + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.CREATETIME DESC ";
		return BizCity.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
	}
	
	public RenderBean save(Controller para) {
		BizCity model = para.getModel(BizCity.class);
		RenderBean renderBean = new RenderBean();
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderBean.setCode(200);
				renderBean.setMessage("更新成功！");
				renderBean.setData(BizCity.dao.findById(model.getId()));
			} else {
				renderBean.setCode(500);
				renderBean.setMessage("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			if (model.save()) {
				renderBean.setCode(200);
				renderBean.setMessage("保存成功！");
				renderBean.setData(BizCity.dao.findById(model.getId()));
				
				try {
					BizCityMenu cityMenu=new BizCityMenu();
					cityMenu.setId(UuidUtil.getUUID());
					cityMenu.setParentId(model.getId());
					cityMenu.setCityId(model.getId());
					cityMenu.setName("图层");
					cityMenu.setCode("Layers");
					cityMenu.setNumber(0);
					cityMenu.setSort(0);
					cityMenu.save();
					
					cityMenu.setId(UuidUtil.getUUID());
					cityMenu.setCityId(model.getId());
					cityMenu.setParentId(model.getId());
					cityMenu.setName("场景");
					cityMenu.setCode("Scenes");
					cityMenu.setNumber(0);
					cityMenu.setSort(1);
					cityMenu.save();
					
					cityMenu.setId(UuidUtil.getUUID());
					cityMenu.setCityId(model.getId());
					cityMenu.setParentId(model.getId());
					cityMenu.setName("底图");
					cityMenu.setCode("Maps");
					cityMenu.setNumber(0);
					cityMenu.setSort(2);
					cityMenu.save();
					
				} catch (Exception e) {
				}
			} else {
				renderBean.setCode(500);
				renderBean.setMessage("保存失败！");
			}
		}
		return renderBean;
	}
	
}
